import {
  fuseSearchFun,
  getImgSrc,
  type ConfigJsonType,
  type GameDataSourceType,
  type GameJson,
  type SearchGameJsonType,
} from "~/utils";
import gameJson from "@/public/json/game.json";
import aboutJson from "@/public/json/about.json";
import themeJson from "@/public/json/theme.json";
import categoryIcon from "@/public/json/categoryIcon.json";

// /** 初始化的时候获取oss-game远程数据，因为远程json获取会失败，暂时不使用 */
// const fetchInitGameData = async (): Promise<GameJson[]> => {
//   const isDev = process.env.NODE_ENV === "development";
//   return new Promise((resolve, reject) => {
//     if (isDev) {
//       resolve(gameJson);
//     } else {
//       fetch("https://h5.assetsres.com/games-v250709.json")
//         .then((res) => {
//           console.log("获取oss数据成功...");
//           resolve(res.json());
//         })
//         .catch((error) => {
//           console.log("获取oss数据失败...");
//           reject(error);
//         });
//     }
//   });
// };

/** 获取游戏数据列表 */
export const fetchInitGameData = (): GameJson[] => {
  return gameJson;
};

/**
 * 获取每个域名下的最终渲染数据对象
 * @param hostName 每个域名值
 * @returns
 */
export const getGameDataSource = (gameDataSourceType: GameDataSourceType) => {
  const { hostName, gameJson, configJson } = gameDataSourceType;
  const getConfig = configJson[hostName as keyof typeof configJson] as unknown as ConfigJsonType; // 拿到配置文件
  const {
    aboutId = 0,
    themeId = 0,
    gameIds = [],
    categoryId = 0,
    iconKey: { start = 0, length = 0 } = {},
    siteName = "",
  } = getConfig || {};
  const allGameJson = gameJson.map((item) => {
    const { img_token = "" } = item;
    const imgNext = img_token.slice(start, start + length);
    const v4Pre = String(item.id);
    return {
      ...item,
      icon: getImgSrc({ imgNext, siteName, v4Pre }),
    };
  });
  const newConfig: ConfigJsonType = {
    ...getConfig,
    aboutJson: aboutJson.find((item) => item.id === aboutId),
    themeJson: themeJson.find((item) => item.id === themeId),
    categoryJson: categoryIcon.find((item) => item.id === categoryId)?.categoryItems || [],
    homeGameJson: gameIds
      .map((gameId) => {
        return allGameJson.find((gameItem) => gameItem.id == gameId) || { id: gameId };
      })
      .filter(Boolean),
    allGameJson,
  };
  return newConfig;
};

/**
 * 模糊匹配数据
 * @param searchGameJsonType
 * @returns
 */
export const getSearchGameJson = (searchGameJsonType: SearchGameJsonType) => {
  const { allGameJson = [], searchValue = "" } = searchGameJsonType;
  if (!searchValue) return [];
  return fuseSearchFun({
    keys: ["type", "name"],
    list: allGameJson,
    value: searchValue,
  });
};
